package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * model.User:xieChao
 * Date:2022/12/4 18:54
 */
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("application/json;charset=utf8");
        BlogDao blogDao = new BlogDao();
        //根据blogId来决定是什么模式
        String param = req.getParameter("blogId");

        if(param==null) {
            //不存在参数，获取博客列表
          List<Blog> blogs = blogDao.selectAll();
          //把blogs对象转为JSON格式
          String respJson = objectMapper.writeValueAsString(blogs);
          resp.getWriter().write(respJson);
      }else{
          //存在参数，获取博客详情
          int blogId = Integer.parseInt(param);
          Blog blog = blogDao.selectOne(blogId);
          String respJson = objectMapper.writeValueAsString(blog);
          resp.getWriter().write(respJson);
      }
    }

    /**
     * 博客的发布功能
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if(session == null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("未登录！！！");
            return;
        }

        User user = (User) session.getAttribute("user");
        if(user == null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("未登录！！！");
            return;
        }

        //一定要先执行编码格式
        req.setCharacterEncoding("utf8");
        //取出参数(博客的标题、正文)
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if(title == null || "".equals(title) || content == null || "".equals(content)){
            //直接告诉客服端 ,请求错误,缺少参数
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("提交内容不得为空！！！");
            return;
        }
        //构造blog对象,把当前信息填充进去，并插入到数据库中
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        //作者id 就是当前提交这个博客用户身份信息
        blog.setUserId(user.getUserId());
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);
        //重定向到，博客列表页
        resp.sendRedirect("blog_list.html");
    }
}
